# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd

from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

import matplotlib.pyplot as plt
import seaborn as sns


# %matplotlib inline

# path to where the data lies
#dpath = './data/'
data = pd.read_csv("./day_preprocessed.csv")
# print(data.head())

# filter data by year
# data_0 = data.query("yr==0")
data_0 = data[data.yr == 0]
data_1 = data[data.yr == 1]
y_train = data_0['cnt'].values
y_test = data_1['cnt'].values
X_train = data_0.drop('cnt', axis = 1).drop('instant', axis = 1)
X_test = data_1.drop('cnt', axis = 1).drop('instant', axis = 1)

#对y做标准化，不是必须
ss_y = StandardScaler()
y_train = ss_y.fit_transform(y_train.reshape(-1,1))
y_test = ss_y.transform(y_test.reshape(-1,1))

#训练集和测试集y的均值差异很大，均值差异用作校正
mean_test_y = y_test.mean()
#归一化后train均值为0
#mean_train_y = 0
mean_diff = mean_test_y;
print("difference between mean of train and test y:", mean_diff)


print("========= 岭回归 =============")
from sklearn.linear_model import  RidgeCV
from sklearn.metrics import r2_score

#设置超参数（正则参数）范围
alphas = [0.01, 0.1, 1.0, 10 ,100, 200 ]
#n_alphas = 20
#alphas = np.logspace(-5,2,n_alphas)

#生成一个RidgeCV实例
ridge = RidgeCV(alphas=alphas, store_cv_values=True)
#模型训练
ridge.fit(X_train, y_train)
#预测
y_test_pred_ridge = ridge.predict(X_test) + mean_diff
y_train_pred_ridge = ridge.predict(X_train)

print ('alpha is:', ridge.alpha_)
# 评估，使用r2_score评价模型在测试集和训练集上的性能
print 'The r2 score of RidgeCV on test is', r2_score(y_test, y_test_pred_ridge)
print 'The r2 score of RidgeCV on train is', r2_score(y_train, y_train_pred_ridge)